package org.jeecg.modules.xl.aftersale.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.xl.aftersale.dto.AftersaleAuditDto;
import org.jeecg.modules.xl.aftersale.entity.XlCustomerAftersale;
import org.jeecg.modules.xl.aftersale.entity.XlCustomerAftersaleDetail;
import org.jeecg.modules.xl.aftersale.service.IXlCustomerAftersaleDetailService;
import org.jeecg.modules.xl.aftersale.service.IXlCustomerAftersaleService;
import org.jeecg.modules.xl.aftersale.vo.XlCustomerAftersalePage;
import org.jeecg.modules.xl.exceltemplate.vo.AfterOrderImportVO;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.entity.XlCustomerOrderDetail;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.order.service.IXlCustomerOrderDetailService;
import org.jeecg.modules.xl.order.service.impl.XlCustomerOrderDetailServiceImpl;
import org.jeecg.modules.xl.order.utils.DictUtils;
import org.jeecg.modules.xl.order.vo.OrderSheet;
import org.jeecg.modules.xl.order.vo.OrderSheetDetail;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description: 售后单
 * @Author: jeecg-boot
 * @Date:   2024-11-03
 * @Version: V1.0
 */
@Api(tags="售后单")
@RestController
@RequestMapping("/xl/xlCustomerAftersale")
@Slf4j
public class XlCustomerAftersaleController {
	@Autowired
	private IXlCustomerAftersaleService xlCustomerAftersaleService;
	@Autowired
	private IXlCustomerAftersaleDetailService xlCustomerAftersaleDetailService;
	@Autowired
	private IXlCustomerOrdeService orderService;
	@Autowired
	private IXlCustomerOrderDetailService orderDetailService;
	 @Autowired
	 private DictUtils dictUtils;
	@Value("${pichost}")
	private String baseUrl;
	/**
	 * 分页列表查询
	 *
	 * @param xlCustomerAftersale
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "售后单-分页列表查询")
	@ApiOperation(value="售后单-分页列表查询", notes="售后单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<XlCustomerAftersale>> queryPageList(XlCustomerAftersale xlCustomerAftersale,
									@RequestParam(name="pageType",required = false) Integer pageType,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<XlCustomerAftersale> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerAftersale, req.getParameterMap());
		Page<XlCustomerAftersale> page = new Page<XlCustomerAftersale>(pageNo, pageSize);
		List<String> statusList = new ArrayList<>();
		statusList.add("1");
		statusList.add("2");
		if (pageType != null && pageType > 0){
			queryWrapper.eq(pageType == 1,"wo_status", dictUtils.getDictValue("audit_state","待审核") );
			queryWrapper.in(pageType == 2,"wo_status", statusList );
		}
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//当前用户的角色
		String roles = user.getRoleCode();

		//是否管理员角色
//		if (!StrUtil.containsAny(roles, CommonConstant.ADMIN_ROLES)) {
		if (StrUtil.containsAny(roles, "slt_customer")) {//是否是采购人员
			queryWrapper.eq("create_by",user.getUsername());
		}
		IPage<XlCustomerAftersale> pageList = xlCustomerAftersaleService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param xlCustomerAftersalePage
	 * @return
	 */

    @RequiresPermissions("slt:Aftersale:addAftersale")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody XlCustomerAftersalePage xlCustomerAftersalePage) {
		XlCustomerAftersale xlCustomerAftersale = new XlCustomerAftersale();
		BeanUtils.copyProperties(xlCustomerAftersalePage, xlCustomerAftersale);
		return xlCustomerAftersaleService.saveMain(xlCustomerAftersale, xlCustomerAftersalePage.getXlCustomerAftersaleDetailList());

	}

	/**
	 *  编辑
	 *
	 * @param xlCustomerAftersalePage
	 * @return
	 */
	@AutoLog(value = "售后单-编辑")
	@ApiOperation(value="售后单-编辑", notes="售后单-编辑")
    @RequiresPermissions("xl:xl_customer_aftersale:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody XlCustomerAftersalePage xlCustomerAftersalePage) {
		XlCustomerAftersale xlCustomerAftersale = new XlCustomerAftersale();
		BeanUtils.copyProperties(xlCustomerAftersalePage, xlCustomerAftersale);
		XlCustomerAftersale xlCustomerAftersaleEntity = xlCustomerAftersaleService.getById(xlCustomerAftersale.getId());
		if(xlCustomerAftersaleEntity==null) {
			return Result.error("未找到对应数据");
		}
		xlCustomerAftersaleService.updateMain(xlCustomerAftersale, xlCustomerAftersalePage.getXlCustomerAftersaleDetailList());
		return Result.OK("编辑成功!");
	}

	 /**
	  *   审核
	  * @return
	  */
	 @AutoLog(value = "售后单-审核")
	 @ApiOperation(value="售后单-审核", notes="售后单-审核")
	 @RequiresPermissions("xl:xl_customer_aftersale:audit")
	 @PostMapping(value = "/audit")
	 public Result<String> audit(@Valid @RequestBody AftersaleAuditDto dto) {
		 return xlCustomerAftersaleService.audit(dto);

	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "售后单-通过id删除")
	@ApiOperation(value="售后单-通过id删除", notes="售后单-通过id删除")
    //@RequiresPermissions("slt:aftersalt:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		xlCustomerAftersaleService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "售后单-批量删除")
	@ApiOperation(value="售后单-批量删除", notes="售后单-批量删除")
    @RequiresPermissions("xl:xl_customer_aftersale:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.xlCustomerAftersaleService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "售后单-通过id查询")
	@ApiOperation(value="售后单-通过id查询", notes="售后单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<XlCustomerAftersale> queryById(@RequestParam(name="id",required=true) String id) {
		XlCustomerAftersale xlCustomerAftersale = xlCustomerAftersaleService.getById(id);
		if(xlCustomerAftersale==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(xlCustomerAftersale);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "售后单明细通过主表ID查询")
	@ApiOperation(value="售后单明细主表ID查询", notes="售后单明细-通主表ID查询")
	@GetMapping(value = "/queryXlCustomerAftersaleDetailByMainId")
	public Result<List<XlCustomerAftersaleDetail>> queryXlCustomerAftersaleDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<XlCustomerAftersaleDetail> xlCustomerAftersaleDetailList = new ArrayList<>();

		//拼接图片

		xlCustomerAftersaleDetailList.addAll(xlCustomerAftersaleDetailService.selectByMainId(id));

		//String baseUrl = "http://47.93.163.105:8058/jeecg-boot/sys/common/static/";
		List<XlCustomerAftersaleDetail> newRecordsList = new ArrayList<>();
		for(XlCustomerAftersaleDetail xlCustomerAftersaleDetail : xlCustomerAftersaleDetailList){
			if(ObjectUtil.isNotEmpty(xlCustomerAftersaleDetail.getMainPic())) {
				xlCustomerAftersaleDetail.setMainPic(baseUrl + xlCustomerAftersaleDetail.getMainPic());
			}else{
				xlCustomerAftersaleDetail.setMainPic(baseUrl+ "/temp/nophoto.png");
			}
			newRecordsList.add(xlCustomerAftersaleDetail);
		}
		return Result.OK(newRecordsList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param xlCustomerAftersale
    */
    @RequiresPermissions("xl:xl_customer_aftersale:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlCustomerAftersale xlCustomerAftersale) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<XlCustomerAftersale> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerAftersale, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<XlCustomerAftersale> xlCustomerAftersaleList = xlCustomerAftersaleService.list(queryWrapper);

      // Step.3 组装pageList
      List<XlCustomerAftersalePage> pageList = new ArrayList<XlCustomerAftersalePage>();
      for (XlCustomerAftersale main : xlCustomerAftersaleList) {
          XlCustomerAftersalePage vo = new XlCustomerAftersalePage();
          BeanUtils.copyProperties(main, vo);
          List<XlCustomerAftersaleDetail> xlCustomerAftersaleDetailList = xlCustomerAftersaleDetailService.selectByMainId(main.getId()+"");
          vo.setXlCustomerAftersaleDetailList(xlCustomerAftersaleDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "售后单列表");
      mv.addObject(NormalExcelConstants.CLASS, XlCustomerAftersalePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("售后单数据", "导出人:"+sysUser.getRealname(), "售后单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	//@RequiresPermissions("lx:xl_customer_orde:importExcel")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setSheetNum(1);	//只导入一个sheet数据
			params.setStartSheetIndex(0);	//从第一个sheet开始导入
			params.setNeedSave(false);
			try {
				List<AfterOrderImportVO> list = ExcelImportUtil.importExcel(file.getInputStream(), AfterOrderImportVO.class, params);

				if(ObjectUtil.isEmpty(list)){
					Result re = new Result();
					re.setSuccess(false);
					re.setMessage("导入失败，excel数据为空，请检查");
					return re;
				}
				//核查售后单是否存在，核查方式：select * from where 单号-upccode in ()
				// 使用 Stream 构造 IN 条件
				String inCondition = list.stream()
						.map(vo -> String.format("('%s', '%s')", vo.getOrderCode(), vo.getUpcCode())) // 格式化每对 (orderCode, upcCode)
						.collect(Collectors.joining(", "));

				List<AfterOrderImportVO>  targetResult = xlCustomerAftersaleDetailService.selectExitAfterOrderOfUpcCode(inCondition);

				if(ObjectUtil.isNotEmpty(targetResult)){
					String exitData = targetResult.stream()
							.map(vo -> String.format("('%s', '%s')", vo.getOrderCode(), vo.getUpcCode())) // 格式化每对 (orderCode, upcCode)
							.collect(Collectors.joining(", "));
					//导入的数据存在售后单，全部数据放弃。
					Result re = new Result();
					re.setSuccess(false);
					re.setMessage("导入失败，"+exitData+"已经存在售后单，请检查数据后重新上传文件。");
					return re;
				}

				//数据唯一性校验成功，开始处理数据

				//根据订单编码进行进行分组
				Map<String, List<AfterOrderImportVO>> groupedByOrderCode = list.stream()
						.collect(Collectors.groupingBy(AfterOrderImportVO::getOrderCode));
				List<XlCustomerAftersalePage> saveObjectList = new ArrayList<>();
				//处理分组结果，每个分组就是一个订单
				for (Map.Entry<String, List<AfterOrderImportVO>> entry : groupedByOrderCode.entrySet()) {
					XlCustomerOrde po = new XlCustomerOrde();
					String orderCode = entry.getKey();//订单编码
					List<AfterOrderImportVO> orderSheetList = entry.getValue();//这是每一个分组list，相当于一个订单
					//查询订单
					QueryWrapper<XlCustomerOrde> ordeQueryWrapper = new QueryWrapper<>();
					ordeQueryWrapper.eq("order_code",orderCode);
					XlCustomerOrde targetXlOrder = orderService.getOne(ordeQueryWrapper);
					if(ObjectUtil.isEmpty(targetXlOrder)){
						Result re = new Result();
						re.setSuccess(false);
						String msg = String.format("导入失败，订单【%s】不存在，请检查数据",orderCode);
						re.setMessage(msg);
						return re;
					}

					//查询订单明细
					QueryWrapper<XlCustomerOrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
					orderDetailQueryWrapper.eq("order_code",orderCode);
					List<XlCustomerOrderDetail>  targetXlOrderDetailList = orderDetailService.list(orderDetailQueryWrapper);
					if(ObjectUtil.isEmpty(targetXlOrderDetailList)){
						Result re = new Result();
						re.setSuccess(false);
						String msg = String.format("导入失败，订单【%s】不存在商品明细，请检查数据",orderCode);
						re.setMessage(msg);
						return re;
					}
					// 转换为 Map，key 为 orderCode，value 为对象本身
					Map<String, XlCustomerOrderDetail> orderDetailMap = targetXlOrderDetailList.stream()
							.collect(Collectors.toMap(
									XlCustomerOrderDetail::getUpcCode, // 键：upcCpde
									detail -> detail                     // 值：对象本身
							));

					//构造AfterOrder
					XlCustomerAftersale xlCustomerAftersale = new XlCustomerAftersale();

					/**售后单状态（0:待审批，1:审批通过,2:审批不通过）*/
					xlCustomerAftersale.setWoStatus("0");
					/**备注*/
					xlCustomerAftersale.setWoNote("批量导入");
					/**售后类型*/
					xlCustomerAftersale.setAftersaleType(orderSheetList.get(0).getAftersaleType());
					/**售后原因*/
					xlCustomerAftersale.setRenson(orderSheetList.get(0).getReason());
					/**订单单号*/
					xlCustomerAftersale.setOrderCode(orderCode);
					/**物流单号*/
					//private String logiCode;
					/**门店编号*/
					xlCustomerAftersale.setStoreCode(targetXlOrder.getStoreCode());
					/**门店编号*/
					xlCustomerAftersale.setStoreName(targetXlOrder.getStoreName());
					/**凭证*/
					xlCustomerAftersale.setWoImage("/temp/afterdefault.png");//设置默认的凭证，避免页面报错
					//构造AfterOrderDetail
					List<XlCustomerAftersaleDetail> xlCustomerAftersaleDetailList = new ArrayList<>();
					for(AfterOrderImportVO temp:orderSheetList){
						XlCustomerAftersaleDetail xlCustomerAftersaleDetail = new XlCustomerAftersaleDetail();

						/**售后单状态（0:待审批，1:审批通过,2:审批不通过）*/
						xlCustomerAftersaleDetail.setWoStatus("0");
						/**orderId*/
						xlCustomerAftersaleDetail.setOrderId(targetXlOrder.getId());
						/**订单编码*/
						xlCustomerAftersaleDetail.setOrderCode(targetXlOrder.getOrderCode());

						XlCustomerOrderDetail xlCustomerOrderDetail1 =  orderDetailMap.get(temp.getUpcCode());
						if(ObjectUtil.isEmpty(xlCustomerOrderDetail1)){
							Result re = new Result();
							re.setSuccess(false);
							String msg = String.format("导入失败，订单【%s】不存在商品【%s】，请检查数据",orderCode, temp.getUpcCode());
							re.setMessage(msg);
							return re;
						}
						/**商品ID*/
						xlCustomerAftersaleDetail.setProductId(xlCustomerOrderDetail1.getProductId());
						/**upcCode*/
						xlCustomerAftersaleDetail.setUpcCode(temp.getUpcCode());
						/**产品价格*/
						xlCustomerAftersaleDetail.setProductPrice(xlCustomerOrderDetail1.getProductPrice());
						/**售后数量*/
						xlCustomerAftersaleDetail.setAftersaleQuantity(BigDecimal.valueOf(Long.parseLong(temp.getAftersaleQuantity())));
						/**售后金额*/
						xlCustomerAftersaleDetail.setAftersaleAmount(xlCustomerAftersaleDetail.getAftersaleQuantity().multiply(xlCustomerAftersaleDetail.getProductPrice()));

						/**售后原因*/
						xlCustomerAftersaleDetail.setReason(temp.getReason());
						xlCustomerAftersaleDetailList.add(xlCustomerAftersaleDetail);

					}
					XlCustomerAftersalePage page = new XlCustomerAftersalePage();
					BeanUtils.copyProperties(xlCustomerAftersale, page);
					page.setXlCustomerAftersaleDetailList(xlCustomerAftersaleDetailList);
					saveObjectList.add(page);//验证通过的数据
				}
				//开始保存数据
				for(XlCustomerAftersalePage saveTem : saveObjectList){
					XlCustomerAftersale xlCustomerAftersale = new XlCustomerAftersale();
					BeanUtils.copyProperties(saveTem, xlCustomerAftersale);
					xlCustomerAftersaleService.saveMain(xlCustomerAftersale, saveTem.getXlCustomerAftersaleDetailList());
				}

				return Result.OK("文件导入成功！数据行数:" + saveObjectList.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.OK("文件导入失败！");
	}

}
